
var deleteRecord = '<i class="fa fa-warning"></i><strong>This action is irreversible.</strong> Are you sure you want to delete this record?';
var deleteRecords = '<i class="fa fa-warning"></i><strong>This action is irreversible.</strong> Are you sure you want to delete these records?';

// toggle minimize and maximize
(function($) {
    $.fn.btPanelCollapse = function(options) {
        var settings = $.extend({
            toggle: '#id',
            state: 'open',
            open: '<i class="fa fa-caret-up fa-lg"></i>',
            close: '<i class="fa fa-caret-down fa-lg"></i>'
        }, options );
        return this.each(function() {
            this.elem = $(this);
            this.toggle = settings.toggle;
            
            if( this.status === 'open') {
                $(this).html('<span><i class="fa fa-caret-up fa-lg"></span>');
            } else {
                $(this).html('<span><i class="fa fa-caret-down fa-lg"></span>');
            }
            
            if( settings.toggle === '#id' ) {
                if( this.elem.data('toggle') !== undefined ) {
                    this.toggle = this.elem.data('toggle');
                } else {
                    this.toggle = this.elem.closest('.panel');
                }
            } else {
                this.toggle = settings.toggle;
            }
            
            $(this).bind('click', function() {
                if( this.status === 'open') {
                    $(this.toggle).find('.panel-body, .panel-footer').slideDown();
                    $(this).html('<span><i class="fa fa-caret-down fa-lg"></span>');
                } else {
                     $(this.toggle).find('.panel-body, .panel-footer').slideUp();
                    $(this).html('<span><i class="fa fa-caret-up fa-lg"></span>');
                }
                this.status = this.status === 'open' ? 'close' : 'open';
            });
            
            return this;
        });
    };
})(jQuery);

// plugin for close button
(function($) {
    $.fn.btClose = function(options) {
        var settings = $.extend({
            close: '#id'
        }, options );
        return this.each(function() {
            this.elem = $(this);
            this.close = settings.close;
            if( settings.close === '#id' ) {
                if( this.elem.data('close') !== undefined ) {
                    this.close = this.elem.data('close');
                } else {
                    this.close = this.elem.closest('.row');
                }
            } else {
                this.close = settings.close;
            }
            $(this).bind('click', function() {
                $(this.close).fadeOut();
            });
            return this;
        });
    };
})(jQuery);

/*
 * General Function for AJAX Calls
 * @param string url URL for ajax call
 * @param string data Serialize data to be passed
 * @param string format Format of the resoponse text,json or xml
 * @returns object
 */
function doAjax(url, data, format)
{
    var response;
    $.ajax({
        type: 'POST',
        url: url,
        dataType: format,
        data: data,
        async: false,
        success: function(res) {
            response = res;
        }
    });
    return response;
}

/*
 * Creates validation rules
 * @access public
 * @param string name name of the input field
 * @param string readableName name of the field may contain spaces
 * @return object validations object with validations
 */
function set_rules(name, readableName, validations) {
    var validation = {};
    var validationsArray = validations.split('|');
    $.each(validationsArray, function( key, value) {
        
        var rule = value.substr(0, value.indexOf('['));
        var param = value.match(/[^[\]]+(?=])/g);
        
        if( rule !== '' && param !== null) {
            
            if( rule === 'equalTo' || rule === 'matches' ) {
                validation['equalTo'] = '#' + param;
            } else if( rule === 'minlength' || rule === 'min_length') {
                validation['minlength'] = param;
            } else if( rule === 'maxlength' || rule === 'max_length') {
                validation['maxlength'] = param;
            } else if( rule === 'max' || rule === 'less_than_equal') {
                validation['max'] = param;
            } else if( rule === 'min' || rule === 'greater_than_equal') {
                validation['min'] = param;
            } else if( rule === 'valid_extensions') {
                var extensions = param.toString().replace(/,/g, '|');
                validation['extension'] = extensions;
            } else {
                validation[rule] = param;
            }

        } else {
            
            if( value === 'email' || value === 'valid_email') {
                validation['email'] = true;
            } else if( value === 'url' || value === 'valid_url') {
                validation['url'] = true;
            } else if( value === 'digits' || value === 'numeric') {
                validation['digits'] = true;
            } else if( value === 'trim' || value === 'xss_clean' || value === 'prep_for_form' || value === 'prep_url' || value === 'strip_image_tags' || value === 'encode_php_tags') {
                // create custom validation if applicable
            } else {
                validation[value] = true;
            }
        }
        
    });
    return validation;
}

/**
 * Adds live form validation to a form
 * @param {string} selector Jquery selector for form/s that will have validation
 * @param {object} rules Rules for validation
 */
function addFormValidation( selector, rules ) {
    $(selector).validate({
        errorElement: 'small',
        errorClass: 'help-block',
        rules: rules,
        errorPlacement:function(error, element) {
            element.parents('.input-size').append( '<div class="clear-fix"></div>' );
            element.parents('.input-size').append( error);
        },
        highlight: function(label) {
            $(label).closest('.form-group').removeClass('has-error has-success').addClass('has-error');
        },
        success: function(label) {
            label.addClass('valid').closest('.form-group').removeClass('has-error has-success').addClass('has-success');
        }
    });
}


$(function() {
    
    /*  ------------------------------------------------------- Elements ---- */
    
    // close button
//    $('.close').btClose({
//    });
    
    // collapse button
//        $('.panel-toggle').btPanelCollapse({
////        toggle: '.panel-body, .panel-footer'
//    });

    // draggable elements
    $('.draggable').draggable({
        handle: '.handle'
    });

    
});



// ------------------------------------------------------------ Datatable

function toDataTable(id, ajaxSource, aoColumns) {
    
    var table = $('#' + id);
    var tableOptions = {};
    
    tableOptions['oLanguage'] = {
        sSearch: '',
        sInfo: '<span>_START_</span> to <span>_END_</span> of <span>_TOTAL_</span>',
        sLengthMenu: '_MENU_',
//        sProcessing: '<img src="' +base_url + 'img/ajax-loader_dark.gif">',
        sEmptyTable: '<h3 class="text-center muted">No Records Available</h3>',
        sZeroRecords: '<h3 class="text-center muted">No Records Available</h3>'
    };
    
    tableOptions['aoColumns'] = aoColumns;
    tableOptions.bProcessing = true;
//    tableOptions.bServerSide = true;
    tableOptions.sAjaxSource = ajaxSource;
    tableOptions.iDisplayLength = 10;
    tableOptions.iDisplayStart = 0;
                
    tableOptions['fnServerData'] = function(sSource, aoData, fnCallback) {
        $.ajax
        ({
            'dataType': 'json',
            'type': 'POST',
            'url': sSource,
            'data': aoData,
            'success': fnCallback
        });
    };
    
    tableOptions.fnDrawCallback = function(oSettings) {
        addEventListeners();
//        if ((typeof (use_modals) === 'undefined') || typeof (use_modals) === null) {
//            if ((typeof (use_ajax) === 'undefined') || typeof (use_ajax) === null) {
//
//            } else {
//                add_ajax();
//            }
//        } else {
//            add_modal(); 
//        }
    };
    
    if(table.hasClass('no-search')) {
        tableOptions['searching'] = false;
    } else {
        tableOptions['searching'] = true;
    }
    
    if(table.hasClass('no-sorting')) {
        tableOptions['ordering'] = false;
    } else {
        tableOptions['ordering'] = true;
    }
    
    if(table.hasClass('no-pagination')) {
        tableOptions['paging'] = false;
        tableOptions['oLanguage'] = {
            sInfo: ''
        };
    } else {
        tableOptions['paging'] = true;
        tableOptions['pagingType'] = 'full_numbers';
        //    tableOptions['sPaginationType'] = 'bootstrap';
        tableOptions['iDisplayStart'] = 0;
        tableOptions['aLengthMenu'] = [[10, 50, 100, -1], [10, 50, 100, 'All']];
        
    }
    
    if( table.hasClass('scroll-x') || table.hasClass('scroll-xy') ) {
        tableOptions['scrollX'] = true;
    }
    
    if( table.hasClass('scroll-y') || table.hasClass('scroll-xy') ) {
        tableOptions['scrollY'] = '200px';
        tableOptions['scrollCollapse'] = true;
    }
    
    if( table.hasClass('text-filter') ) {
        // add header filters
        var headFilters = $('<tr class="search-filters" />');
        $('#' +id+ ' thead th').each( function () {
            var title = $('#' +id+ ' thead th').eq( $(this).index() ).text();
            headFilters.append( '<th><input type="text" class="form-control" placeholder="Search '+title+'" /></th>' );
        } );
        $('#' +id+ ' thead').prepend(headFilters);
    }
    
    if( table.hasClass('dropdown-filter') ) {
        // add header filters
        var headFilters = $('<tr class="search-filters" />');
        $('#' +id+ ' thead th').each( function () {
            var title = $('#' +id+ ' thead th').eq( $(this).index() ).text();
            headFilters.append( '<th><input type="text" class="form-control" placeholder="Search '+title+'" /></th>' );
        } );
        $('#' +id+ ' thead').prepend(headFilters);
    }

    // Initialize DataTable
    var dataTable = table.DataTable(tableOptions);
     
    if( table.hasClass('text-filter') ) {
        // Apply the filter
        $('#' + id + ' thead input').on('keyup change', function() {
            dataTable
                    .column($(this).parent().index() + ':visible')
                    .search(this.value)
                    .draw();
        });
    }
    
    if( table.hasClass('dropdown-filter') ) {
        $('#' + id + ' tfoot th').each(function(i) {
            var select = $('<select class="form-control"><option value=""></option></select>')
                    .appendTo($(this).empty())
                    .on('change', function() {
                dataTable.column(i)
                        .search($(this).val())
                        .draw();
            });

            dataTable.column(i).data().unique().sort().each(function(d, j) {
                select.append('<option value="' + d + '">' + d + '</option>');
            });
        });
    }
    
    // search
    $('.dataTables_filter input').unwrap();
    $('.dataTables_filter input').attr("placeholder", "Search Term");
    $('.dataTables_filter input').addClass("form-control input-sm");
    $('.dataTables_filter input').wrap('<div class="input-group" />');
    $('.dataTables_filter input').parent().append('<span class="input-group-btn"><button type="submit" class="btn btn-default btn-sm"><i class="fa fa-search"></i></button></span>');
     
    // limit
    $('.dataTables_length select').addClass("form-control input-sm");
}

function datatable_init(id, ajaxSource, aoColumns, filter) {
    
    var table = $('#' + id);
    
    var opt = {};
                
    opt.oLanguage = {
        sSearch: '<span>Search:</span> ',
        sInfo: 'Showing <span>_START_</span> to <span>_END_</span> of <span>_TOTAL_</span> entries',
        sLengthMenu: '<span>Show entries:</span> _MENU_',
        sProcessing: '<img src="' +base_url + 'img/ajax-loader_dark.gif">',
        sEmptyTable: '<h3 class="text-center muted">No Records Available</h3>'
    };
                
    opt.sPaginationType = 'full_numbers';
    opt.iDisplayLength = 10;
    opt.iDisplayStart = 0;
    opt.bAutoWidth = false;

    opt.aoColumns = aoColumns;
                
//                opt.aoColumnDefs = [{
//                    bSortable: !1,
//                    aTargets: [0,6]
//                }];
                
    opt.sDom = "lfrtip";

    opt.bProcessing = true;
    opt.bServerSide = true;
    opt.sAjaxSource = ajaxSource;
    opt.iDisplayLength = 10;
    opt.iDisplayStart = 0;
                
    opt.fnServerData = function(sSource, aoData, fnCallback) {
        $.ajax
        ({
            'dataType': 'json',
            'type': 'POST',
            'url': sSource,
            'data': aoData,
            'success': fnCallback
        });
    };
                
//    opt.fnDrawCallback = function(oSettings) {
//        make_rows_selectable();
//        if ((typeof (use_modals) === 'undefined') || typeof (use_modals) === null) {
//            if ((typeof (use_ajax) === 'undefined') || typeof (use_ajax) === null) {
//
//            } else {
//                add_ajax();
//            }
//        } else {
//            add_modal(); 
//        }
//    };
                
    if(table.hasClass("dataTable-noheader")){
        opt.bFilter = false;
        opt.bLengthChange = false;
    }
    if(table.hasClass("dataTable-nofooter")){
        opt.bInfo = false;
        opt.bPaginate = false;
    }
    if(table.hasClass("dataTable-nosort")){
        var column = table.attr('data-nosort');
        column = column.split(',');
        for (var i = 0; i < column.length; i++) {
            column[i] = parseInt(column[i]);
        }
        opt.aoColumnDefs =  [{ 
            'bSortable': false, 
            'aTargets': column 
        }];
    }
    if(table.hasClass("dataTable-scroll-x")){
        opt.sScrollX = "100%";
        opt.bScrollCollapse = true;
        $(window).resize(function(){
            oTable.fnAdjustColumnSizing();
        });
    }
    if(table.hasClass("dataTable-scroll-y")){
        opt.sScrollY = "300px";
        opt.bPaginate = false;
        opt.bScrollCollapse = true;
        $(window).resize(function(){
            oTable.fnAdjustColumnSizing();
        });
    }
    if(table.hasClass("dataTable-reorder")){
        opt.sDom = "R"+opt.sDom;
    }
    if(table.hasClass("dataTable-colvis")){
        opt.sDom = "C"+opt.sDom;
        opt.oColVis = {
            "buttonText": "Change columns <i class='icon-angle-down'></i>"
        };
    }
    if(table.hasClass('dataTable-tools')){
        opt.sDom= "T"+opt.sDom;
        opt.oTableTools = {
            "sSwfPath": "js/plugins/datatable/swf/copy_csv_xls_pdf.swf"
        };
    }
    if(table.hasClass("dataTable-scroller")){
        opt.sScrollY = "300px";
        opt.bDeferRender = true;
        if(table.hasClass("dataTable-tools")){
            opt.sDom = 'TfrtiS';
        } else {
            opt.sDom = 'frtiS';
        }
    }
    if(table.hasClass("dataTable-grouping") && table.attr("data-grouping") == "expandable"){
        opt.bLengthChange = false;
        opt.bPaginate = false;
    }

    dataTable = table.dataTable(opt);
    table.css("width", '100%');
    $('.dataTables_filter input').attr("placeholder", "Search here...");
    
//                $(".dataTables_length select").wrap("<div class='input-mini'></div>").chosen({
//                    disable_search_threshold: 9999999
//                });

    $(".dataTables_length select").wrap("<div class='input-mini'></div>");

    $("#check_all").click(function(e){
        $('input', dataTable.fnGetNodes()).prop('checked',this.checked);
    });
    if(table.hasClass("dataTable-fixedcolumn")){
        new FixedColumns( dataTable );
    }
    if(table.hasClass("dataTable-columnfilter")){
        dataTable.columnFilter({
            "sPlaceHolder" : "head:after",
            sRangeFormat: "{from}{to}",
            aoColumns: filter
        });
    }
    if(table.hasClass("dataTable-grouping")){
        var rowOpt = {};

        if(table.attr("data-grouping") == 'expandable'){
            rowOpt.bExpandableGrouping = true;
        }
        dataTable.rowGrouping(rowOpt);
    }
}

/**
 * Add event handler for check-all checkboxes
 * @acess public
 */
function checkAllEventHandler() {
    $('.check-all').on('click', function() {
        var record = $(this).data('check');
        if ($(this).prop('checked')) {
            $('input[class=' + record + ']').prop('checked', true);
        } else {
            $('input[class=' + record + ']').attr('checked', false);
        }
    });
}